package org.example.demo;

import com.mysql.cj.jdbc.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.MessageFormat;
import java.util.Scanner;

public class demo3_DataSource {
    public static void main(String[] args) {
        //定义mysql数据源对象
        MysqlDataSource mysqlDataSource = new MysqlDataSource();
        //设置数据库的连接串
        mysqlDataSource.setURL("jdbc:mysql://127.0.0.1:3306/mysql123?characterEncoding=utf8" +
        "&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true&useSSL=false");
        //设置用户名
        mysqlDataSource.setUser("root");
        //设置密码
        mysqlDataSource.setPassword("123456");
        //定义JDBC的数据源对象
        DataSource dataSource = mysqlDataSource;

        //声明数据库连接对象
        Connection connection = null;
        //声明SQL语句的预处理对象
        PreparedStatement statement = null;
        //结果集
        ResultSet resultSet = null;

        try {
            //1.获取数据库连接
            connection = dataSource.getConnection();
            //2.定义sql语句
            String sql = "select id,name from users where name = ?";
            //接收用户输入的姓名
            System.out.println("请输入要查询的姓名-->");
            Scanner scanner = new Scanner(System.in);
            String inputName = scanner.next();
            //获取sql预处理对象
            statement = connection.prepareStatement(sql);
            //3.用真实的姓名去替换占位符
            statement.setString(1,inputName);
            //4.执行sql语句
            resultSet = statement.executeQuery();
            while (resultSet.next()) {
                //每进入一次循环表示读取一行新记录
                //获取id列的值，根据列的数据类型不同调用不同的方法
                long id = resultSet.getLong("id");
                //依次获取其他列的值
                String name = resultSet.getString("name");
                System.out.println(MessageFormat.format("编号={0},姓名={1}",id,name));
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            if (resultSet != null){
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }

            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }

            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}


























